package com.xmlt.core.template.expression;

import java.util.Map;

import com.xmlt.core.template.instance.AbstractInstance;
import com.xmlt.core.template.instance.InstanceReference;
import com.xmlt.core.template.instance.MultiInstance;
import com.xmlt.core.template.instance.Value;

import ognl.OgnlContext;
import ognl.OgnlException;
import ognl.PropertyAccessor;

public class InstancePropertyAccessor implements PropertyAccessor {
	public static boolean resolve = false;

	@Override
	public Object getProperty(Map context, Object target, Object name)
			throws OgnlException {
		if (!(target instanceof AbstractInstance))
			throw new OgnlException("this accessor can only handle instances.");
		AbstractInstance instance = (AbstractInstance) target;
		if (instance instanceof InstanceReference) {
			if (!((InstanceReference) instance).validate()) {
				return null;
			}
		}
		AbstractInstance result = null;

		if (name instanceof Integer) {
			if (instance instanceof MultiInstance) {
				result = ((MultiInstance) instance).getChildren().get(
						(Integer) name);
			} else {
				throw new OgnlException(
						"indices can only be set on multi-instance.");
			}
		} else {
			result = instance.lookup((String) name);
			if (resolve && result instanceof Value) {
				return ((Value) result).getValue();
			}
		}

		return result;
	}

	@Override
	public String getSourceAccessor(OgnlContext context, Object target,
			Object index) {
		return "";
	}

	@Override
	public String getSourceSetter(OgnlContext context, Object target,
			Object index) {
		return "";
	}

	@Override
	public void setProperty(Map context, Object target, Object name,
			Object value) throws OgnlException {
	}

}
